//
//  LLPlayerVM.swift
//  新印象
//
//  Created by wyl on 2016/12/22.
//  Copyright © 2016年 魏延龙. All rights reserved.
//

import UIKit

protocol LLPlayVMDelegate {
    func didfinishCurrentValue(duration : String)
    func didfinishTotalValue(duration : String)
    func progressValue(float : Float)
    func didfinishGetSongName(songname : String,fileName : String)
    func updateTable(indexPath:IndexPath)
    func updateTableView()
}

class LLPlayerVM: NSObject,LLPlayManagerDelegate {

    var plmanager = LLPlayManager()
    let songInfo = songModel()
    var MusicModelArr = [LLMusicModel]()
    var index : Int!
    var delegate : LLPlayVMDelegate?
    
    var timeArr = [String]()
    var wordArr = [String]()
    
    var timer : Timer!
    var indexPath : IndexPath? = nil
    
    
    override init() {
        super.init()
        plmanager.delegate = self
    }

    // MARK: 获得播放地址
    func playinfo(completeSuccess: @escaping ()-> Void,completeFailed: @escaping ()-> Void) {
        let url = "http://apis.baidu.com/geekery/music/playinfo"
        let parameters = ["hash":MusicModelArr[index].hash]
        LLNetManager.netGet(url: url, parameters: parameters as Dictionary<String, AnyObject>, completionHandlerSuccess: { (dic) in
            let dataDic = dic["data"] as! Dictionary<String, AnyObject>
            self.songInfo.url = dataDic["url"] as? String
            self.songInfo.fileName = dataDic["fileName"] as? String
            self.songInfo.singerName = dataDic["singerName"] as? String
            self.songInfo.songName = dataDic["songName"] as? String
            self.songInfo.timeLength = dataDic["timeLength"] as? String
            print("获得地址成功",self.songInfo.url!)
            self.plmanager.url = self.songInfo.url!
            self.delegate?.didfinishGetSongName(songname: self.songInfo.songName!, fileName: self.songInfo.fileName!)
            completeSuccess()
        }, completionHandlerFailure: { (error) in
            completeFailed()
            print("获得地址失败",error)
            self.playinfo(completeSuccess: { 
                
            }, completeFailed: {
                
            })
        })
        
        playkrc(completeSuccess: {
            self.indexPath = nil
            self.delegate?.updateTableView()
            print("获取歌词成功")
        }) { 
            print("获取歌词失败")
            self.playkrc(completeSuccess: { 
                
            }, completeFailed: {
                
            })
        }
    }
    
    // MARK: 获得歌词
    
    func playkrc(completeSuccess: @escaping ()-> Void,completeFailed: @escaping ()-> Void) {
        let url = "http://apis.baidu.com/geekery/music/krc"
        let parameters = ["name":MusicModelArr[index].filename!,"hash":MusicModelArr[index].hash!,"time":String(describing: MusicModelArr[index].duration!)] as [String : Any]
        LLNetManager.netGet(url: url, parameters: parameters as Dictionary<String, AnyObject>, completionHandlerSuccess: { (dic) in
            let irc = dic["data"]?["content"] as! String
            let sepArr = irc.components(separatedBy: "[")
            self.timeArr.removeAll()
            self.wordArr.removeAll()
            for i in 0..<sepArr.count {
                if (sepArr[i].characters.count > 0){
                    let arr = sepArr[i].components(separatedBy: "]")
                    self.timeArr.append(arr[0])
                    self.wordArr.append(arr[1])
                }
            }
            self.timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
            self.timer.fire()
            completeSuccess()
        }, completionHandlerFailure: { (error) in
            completeFailed()
        })
    }
    
    func playMusic() {
        plmanager.playUrl()
    }
    
//    func play() {
//        plmanager.play()
//    }
    
    func pause() {
        plmanager.pause()
    }
    
    func stop() {
        plmanager.stop()
    }
    func next() {
        index = index + 1
        playinfo(completeSuccess: { 
            self.plmanager.next()
        }, completeFailed: {
            self.index = self.index - 1
        })
    }
    
    func last() {
        index = index - 1
        playinfo(completeSuccess: {
            self.plmanager.last()
        }, completeFailed: {
            self.index = self.index + 1
        })
    }
    
    func progressValue() -> Float {
        
        return 1.0
    }
    
    func totalValueDidUpdate(duration: durationSong) {
        let minute = String(describing: duration.minute!)
        let second = String(describing: duration.second!)
        let string = String.Format(string: minute) + ":" +  String.Format(string: second)//minute + ":" + second
        delegate?.didfinishTotalValue(duration: string)
    }
    
    func currentValueDidUpdate(duration: durationSong) {
        let minute = String(describing: duration.minute!)
        let second = String(describing: duration.second!)
        let string = String.Format(string: minute) + ":" +  String.Format(string: second)//minute + ":" + second
        delegate?.didfinishCurrentValue(duration: string)
    }
    
    func progressValue(value: Float) {
        delegate?.progressValue(float: value)
    }
    
    func updateTime() {
        let currentTime = self.plmanager.FSAudio.currentTimePlayed
        let current = Float(currentTime.minute * 60) + Float(currentTime.second)
        for i in 0..<self.timeArr.count {
            let arr = self.timeArr[i].components(separatedBy: ":")
            let irctime = Float(arr[0])! * 60 + Float(arr[1])!
            if current >= irctime {
                indexPath = IndexPath(row: i, section: 0)
                delegate?.updateTable(indexPath: indexPath!)
            } else {
                break
            }
        }
    }
    
    func downLoadMusic(completionProgress : @escaping (_ progress : Double) -> Void){
        LLNetManager.downLoad(string: self.songInfo.url!, fileName: self.songInfo.fileName!) { (progress) in
            completionProgress(progress)
        }
    }
    
    deinit {
        print("playerVM deinit")
    }
    
    // MARK: 对歌单的tableView的处理
    func numofRowsInListtableView() ->Array<Any>{
        return LLFileManagerTool.sharemanager.queryFile(path: "file1")
    }
}
extension String {
    static func Format(string : String) -> String {
        var format = ""
        if (string.characters.count == 1) {
            format = "0" + string
        }else {
            format = string
        }
        return format
    }
}
